const QualificationDao = require('../dao/qualification');
const ValidatorQualification = require('../validators/qualification');
const ok = require('../core/response-shortcut');
const fs = require('fs')

class QualificationController {
    /**
     * 仅限post
     * 创建或更新qualification
     * @param ctx
     */
    static async cuQualification(ctx) {
        // 接收客户端参数
        let req = ctx.request.body;
        //验证器,如果验证不通过,直接在验证器里报错
        await ValidatorQualification.cuQualification(req)
        //验证通过,就操作数据库
        //===>创建qualification并写入sql
        if (req.id) {
            await QualificationDao.uQualification(req);
        } else { 
            await QualificationDao.cQualification(req);
        }

        //===>取出所有qualification
        var arr_allQualification = await QualificationDao.getAllQualification();
        //===>写入txt文件
        fs.writeFile('./config/qualification.txt', '{"qua":' + JSON.stringify(arr_allQualification) + '}', function () {
            console.log('写完了,所有权限生成txt文件了,可用来映射')
        })
        ctx.response.status = 200;
        ctx.body = ok.success()
    }

    static async rdQualification(ctx) {
        /**
         * 仅限get
         * 读取或删除qualification
         * 可读取单个或所有
         * api和id参数皆为空,则读取所有
         * api为空,但id有值,读取单个权限对应的中文
         * api为del,则id必填,删除单个权限
         * @param ctx
         */
        // 接收客户端参数
        let params = ctx.request.query;

        if (params.id) {
            //验证器,如果验证不通过,直接在验证器里报错
            await ValidatorQualification.rdQualification(params.id)
            //===>去数据库搜索id
            ctx.response.status = 200;
            if (params.api === 'del') {
                let data = await QualificationDao.dQualification(params.id);
                //删除成功返回1,否则是0
                if (data == 1) {
                    ctx.body = ok.success('删除成功')
                } else {
                    ctx.body = ok.fail('删除失败,可能未找到对应id')
                }
            } else {
                //读取某个id对应权限的中文名
                let data = await QualificationDao.rQualification(params.id);
                ctx.body = ok.json(data)
            }
        } else {
            //===>取出所有qualification
            var arr_allQualification = await QualificationDao.getAllQualification();
            ctx.response.status = 200;
            ctx.body = ok.json(arr_allQualification)
        }
    }
}

module.exports = QualificationController
